package com.tzx.socketdemo;

import android.os.Bundle;
import android.os.Handler;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

/**
 * Created by tanzhenxing
 * Date: 2016/10/10.
 * Description:
 */
public class TcpSocketActivity extends AppCompatActivity {
    //服务端地址
    private final static String serverIp = "10.252.152.137";
    //服务端口号
    private final static int serverPort = 9999;
    //控件
    private TextView showTv;
    private EditText contentEdt;
    private Button sendBtn;
    //tcp套接字客户端
    private TCPSocketClient tcpSocketClient;
    //自定义Handler
    private Handler handler = new Handler();

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.upd_activity_main);
        showTv = (TextView) findViewById(R.id.content);
        contentEdt = (EditText) findViewById(R.id.edit);
        sendBtn = (Button) findViewById(R.id.send);
        //初始化tcp套接字客户端
        tcpSocketClient = new TCPSocketClient(serverIp, serverPort, new TCPSocketClient.TcpSocketListener() {
            @Override
            public void callBackContent(final String content) {
                handler.post(new Runnable() {
                    @Override
                    public void run() {
                        if (showTv != null && !TextUtils.isEmpty(content)) {
                            showTv.setText(showTv.getText().toString() + content);
                        }
                    }
                });
            }

            @Override
            public void clearInputContent() {
                if (contentEdt != null) {
                    handler.post(new Runnable() {
                        @Override
                        public void run() {
                            contentEdt.setText("");
                        }
                    });
                }
            }
        });
        tcpSocketClient.startTcpSocketConnect();

        sendBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String msg = contentEdt.getText().toString().trim();
                tcpSocketClient.sendMessageByTcpSocket(msg);
            }
        });
    }

    @Override
    protected void onDestroy() {
        if (tcpSocketClient != null) {
            tcpSocketClient.sendMessageByTcpSocket("exit");
        }
        super.onDestroy();
    }
}
